<template>
  <div class="page-box">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Transaction Details</span>
        </div>
      </template>
      <div class="card-content">
        <el-descriptions :column="1" border v-loading="loading">
          <el-descriptions-item label="Transaction Hash" label-align="right" :min-width="140">
            {{ txInfo.hash }}
          </el-descriptions-item>
          <el-descriptions-item label="Status" label-align="right">
            <el-tag v-if="txInfo.status === 1" size="small" type="success">Success</el-tag>
            <el-tag v-if="txInfo.status === 0" size="small" type="danger">Fail</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Block Number" label-align="right">
            {{ txInfo.blockNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="Timestamp" label-align="right">
            {{ txInfo.timestamp }}
          </el-descriptions-item>
          <el-descriptions-item label="From" label-align="right">
            {{ txInfo.from }}
          </el-descriptions-item>
          <el-descriptions-item label="To" label-align="right">
            {{ txInfo.to }}
          </el-descriptions-item>
          <el-descriptions-item
            label="Tokens Transferred"
            :min-width="140"
            label-align="right"
            v-if="transferInfo.length > 0"
          >
            <div
              class="transfer"
              v-for="(item, index) in transferInfo"
              :key="`${index}-transferInfo`"
            >
              <div class="flex">
                <span>From: </span>
                <el-tooltip effect="dark" :content="item.from" placement="top">
                  <span>{{ item.from }}</span>
                </el-tooltip>
                <span>To: </span>
                <el-tooltip effect="dark" :content="item.to" placement="top">
                  <span>{{ item.to }}</span>
                </el-tooltip>
                <span :title="item.address">for value: {{ item.value }}</span>
              </div>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="Value" label-align="right">
            {{ txInfo.txValue }} ETH
          </el-descriptions-item>
          <el-descriptions-item label="Nonce" label-align="right">
            {{ txInfo.nonce }}
          </el-descriptions-item>
          <el-descriptions-item label="Gas-price" label-align="right">
            {{ txInfo.gasPrice }} wei
          </el-descriptions-item>
          <el-descriptions-item label="Gas-limit" label-align="right">
            {{ txInfo.gasLimit }}
          </el-descriptions-item>
          <el-descriptions-item label="Used-gas" label-align="right">
            {{ txInfo.gasUsed }}
          </el-descriptions-item>
          <el-descriptions-item label="Gas Fees" label-align="right">
            Base: {{ txInfo.baseFeePerGas }} Gwei<span style="margin: 0 10px; color: #999">|</span>
            Max: {{ txInfo.maxFeePerGas }} Gwei<span style="margin: 0 10px; color: #999">|</span>
            Max Priority: {{ txInfo.maxPriorityFeePerGas }} Gwei
          </el-descriptions-item>

          <el-descriptions-item label="Input Data" label-align="right">
            <div class="input-data">
              <el-input
                v-model="inputData"
                :autosize="{ minRows: 3, maxRows: 6 }"
                type="textarea"
                :readonly="true"
              />
              <div class="opt">
                <el-button type="primary" @click="handleDefault">Default View</el-button>
                <el-button type="primary" @click="handleDecode">Decode Input Data</el-button>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <!-- <el-tabs type="border-card" class="block">
          <el-tab-pane label="Details"> </el-tab-pane>
          <el-tab-pane label="Logs">
          <div class="logs-list">
              <div class="item" v-for="(item, index) in topicList" :key="index">
                <div class="topic">
                  <span class="name">Address</span>
                  <router-link
                    class="value"
                    v-if="item.address"
                    :to="{
                      name: 'contract',
                      params: { contract: item.address },
                    }"
                    >{{ item.address }}
                  </router-link>
                </div>
                <div class="topic">
                  <span class="name">Topic {{ index }}</span>
                  <span class="value">{{ item.topic }}</span>
                </div>
                <div class="topic">
                  <span class="name">signature</span>
                  <span class="value">{{ item.signature }}</span>
                </div>
                <div class="topic">
                  <span class="name">Name</span>
                  <span class="value">{{ item.name }}</span>
                </div>
                <div class="topic">
                  <span class="name">Args</span>
                  <span class="value bg">
                    <span v-for="(arg, i) in item.args" :key="`${i}-arg`">
                      {{ i + 1 }}： {{ arg }}
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs> -->
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { contract_full_abi } from '@/hooks/contract'
import { useConnectorStore } from '@/stores/connector'
import { utils } from 'ethers'
import { onMounted, ref, toRaw } from 'vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'

type transfer = {
  from: string
  to: string
  value: string
  address: string
}
type TX_INFO = {
  blockHash?: string
  blockNumber?: number
  from?: string
  to?: string
  hash?: string
  nonce?: number
  txValue?: string
  gasLimit?: string
  gasPrice?: string
  gasUsed?: string
  baseFeePerGas?: string
  maxFeePerGas?: string
  maxPriorityFeePerGas?: string
  status?: number // 0失败。 1成功
  timestamp?: string
  inputData: string
}
const route = useRoute()
const inputData = ref('')
const txInfo = ref<TX_INFO>({
  inputData: '',
})
const transferInfo = ref<transfer[]>([])
// const topicList = ref<any>([])
const transactionDescription = ref<any>({})

const handleDefault = () => {
  inputData.value = txInfo.value.inputData
}
const handleDecode = () => {
  const { signature, sighash, args, functionFragment } = transactionDescription.value

  let data = args.map((v: any, i: number) => {
    const { baseType, name, type } = functionFragment.inputs[i]
    let str = `[${i}] : `
    let array = []
    switch (baseType) {
      case 'string':
        str += `${name} - ${v}`
        break
      case 'address':
        str += `${name} - ${v} (${type})`
        break
      case 'array':
        array = v.map((j: any, ind: number) => {
          return `  array[${ind}] - ${name} - ${j.toString()} (${type})`
        })
        str += ' \n ' + array.join(' \n ')
        break
      case 'uint256':
        str += `${name} - ${v.toString()} (${type})`
        break
      default:
        break
    }
    return str
  })
  const argsStr = data.join(' \n ')

  inputData.value = ` Function: ${signature} *** \n MethodID: ${sighash} \n Args: \n ${argsStr}`
}

const connectorStore = useConnectorStore()
const connect = toRaw(connectorStore.connect)

const loading = ref(true)
onMounted(async () => {
  const provider = connect.provider
  const tx_hash = route.params.hash as string

  if (tx_hash.length !== 66 || tx_hash.indexOf('0x') != 0) {
    ElNotification({
      title: 'Warning',
      message: 'Hash格式错误',
      type: 'warning',
    })
    return
  }
  if (!provider) return
  const info = await provider.getTransaction(tx_hash)
  if (!info || !info.blockNumber) {
    console.log('hash error')
    return
  }
  const block = await provider.getBlock(info.blockNumber)
  const receipt = await provider.getTransactionReceipt(tx_hash)

  loading.value = false
  txInfo.value = {
    blockHash: info.blockHash,
    blockNumber: info.blockNumber,
    from: info.from,
    to: info.to,
    hash: info.hash,
    nonce: info.nonce,
    txValue: utils.formatEther(info.value.toString()),
    gasLimit: info.gasLimit.toString(),
    gasPrice: info?.gasPrice?.toString(),
    gasUsed: receipt.cumulativeGasUsed.toString(),
    baseFeePerGas: block.baseFeePerGas ? utils.formatUnits(block.baseFeePerGas, 9) : '--',
    maxFeePerGas: info.maxFeePerGas ? utils.formatUnits(info.maxFeePerGas, 9) : '--',
    maxPriorityFeePerGas: info.maxPriorityFeePerGas
      ? utils.formatUnits(info.maxPriorityFeePerGas, 9)
      : '--',
    status: receipt.status, // 0失败。 1成功
    timestamp: dayjs.unix(block.timestamp).format('YYYY-MM-DD HH:mm:ss'),
    inputData: info.data,
  }
  inputData.value = info.data

  const iface = new utils.Interface(contract_full_abi)
  transactionDescription.value = iface.parseTransaction(info)

  // 默认解析
  handleDecode()
  // for (let i = 0; i < receipt.logs.length; i++) {
  //   const v = receipt.logs[i];
  //   let log = iface.parseLog(v);
  //   const args = log.args;
  //   topicList.value.push(log);
  //   if (log.name === "Transfer") {
  //     transferInfo.value.push({
  //       address: v.address,
  //       from: args.from,
  //       to: args.to,
  //       value: args.value.toString(),
  //     });
  //   }
  // }
})
</script>

<style scoped lang="less">
.opt {
  margin-top: 8px;
}
</style>
